import re

from xml2excel_2 import XmlGenerator


class Lang:
    def __init__(self, key, en, de):
        self.key = key
        self.en = en
        self.de = de

    def set_en(self, en):
        self.en = en

    def set_de(self, de):
        self.de = de

    @classmethod
    def find_for_de(cls, collection, key, de):
        for lang in collection:
            if key == lang.key:
                lang.de = de
                return
        collection.append(Lang(key, None, de))

    @classmethod
    def find_for_en(cls, collection, key, en):
        for lang in collection:
            if key == lang.key:
                lang.en = en
                return
        collection.append(Lang(key, en, None))


class Xml2Excel:
    def __init__(self, collection, en):
        self.collection = collection
        self.en = en
        file_path = None
        if en:
            file_path = '/Users/h/Desktop/strings.xml'
        else:
            file_path = '/Users/yong.hu/AndroidStudioProjects/patpat/Patpat/src/main/res/values-de/strings.xml'
        f = open(file_path)
        self.file_content = f.read()
        f.close()

    def handle_array(self, key):
        regex = '<' + key + '\s+name\s*=\s*"([^"]+)"\s*>([\s\S]+?)</\s*' + key + '\s*>'
        array_regex = re.compile(r'' + regex)
        array_regex_result = array_regex.findall(self.file_content)
        for block in array_regex_result:
            key_name = block[0]
            block_regex = re.compile(r'<item[^>]*>([\s\S]+?)</\s*item\s*>')
            block_regex_result = block_regex.findall(block[1])
            i = 0
            for item in block_regex_result:
                if self.en:
                    Lang.find_for_en(self.collection, key_name + '_' + str(i), item)
                else:
                    Lang.find_for_de(self.collection, key_name + '_' + str(i), item)
                i += 1

    def doIt(self):
        self.handle_array('plurals')

        self.handle_array('string-array')
        regex = re.compile(r'<string\s+name\s*=\s*"([^"]+)"\s*>([\s\S]+?)</\s*string\s*>')
        regex_result = regex.findall(self.file_content)

        for item in regex_result:
            if self.en:
                Lang.find_for_en(self.collection, item[0], item[1])
            else:
                Lang.find_for_de(self.collection, item[0], item[1])


if __name__ == '__main__':
    g = XmlGenerator()
    collection = []

    obj = Xml2Excel(collection, True)

    obj2 = Xml2Excel(collection, False)
    obj.doIt()
    obj2.doIt()
    g.reset_row_index()
    for lang in collection:
        g.write(lang.key, lang.en, lang.de)
    g.done()
